package com.skychyn.webdata;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;

import android.util.Log;

public class URLInputStream {
	// ===========================================================
	// Fields
	// ===========================================================
	private String url;
	private URL myURL;
	private InputStream is;
	private String ip;
	private int port;
	private boolean useProxy;

	// ===========================================================
	// Ctor
	// ===========================================================
	public URLInputStream(String url) {
		this.url = url;
	}

	// ===========================================================
	// Private Methods
	// ===========================================================
	/* Define the URL we want to load data from. */
	private boolean makeURL(String url) {
		try {
			myURL = new URL(url);
			return true;
		} catch (MalformedURLException e) {
			myURL = null;
			Log.e("URLInputStream", "makeURLFail", e);
			return false;
		}
	}

	/* Define InputStream to read from the URLConnection. */
	private boolean getBIS() {
		try {
			// If we use Proxy - configure it before getting
			// an input stream
			if (useProxy) {
				Proxy p = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip,
						port));

				is = myURL.openConnection(p).getInputStream();
			}

			// Just jet input stream without any Proxy
			else
				is = myURL.openConnection().getInputStream();
			return true;
		} catch (IOException e) {
			is = null;
			Log.e("URLInputStream", "getBISFail", e);
			return false;
		}
	}

	// ===========================================================
	// Public Methods
	// ===========================================================

	// Without Proxy
	public InputStream getInputStream() {
		
		useProxy = false;	
		
		// If we can create URL connection
		if (makeURL(url))
			// and get an input stream - return it
			if (getBIS())
				return is;

		// Othervise - return null
		return null;
	}

	// With Proxy
	public InputStream getInputStream(String ip, int port) {
		
		this.ip = ip;
		this.port = port;
		useProxy = true;	
		
		// If we can create URL connection
		if (makeURL(url))
			// and get an input stream - return it
			if (getBIS())
				return is;

		// Othervise - return null
		return null;
	}

	public void closeInputStream() {
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("URLInputStream", "CloseInputStreamFail", e);
		}
	}

}